//
//  UIView+SGExtension.swift
//  QingLiuSwift
//
//  Created by xyanl on 2024/11/11.
//  Copyright © 2024 考拉🐨. All rights reserved.
//

import UIKit

extension UIView: SpadgerCompatible {}

// MARK: - 控制器
extension UIView {
    
    /// 获取 view 当前所在的 controller
    var viewController: UIViewController? {
        var next = superview
        while next != nil {
            let nextResponder = next?.next
            if nextResponder is UINavigationController ||
                nextResponder is UIViewController {
                return nextResponder as? UIViewController
            }
            next = next?.superview
        }
        return nil
    }
    
    /// 获取 view 当前所在的 controller
    var controller: UIViewController? {
        findController(with: UIViewController.self)
    }
    
    var navigationController: UIViewController? {
        findController(with: UINavigationController.self)
    }
    
    var tabbarController: UITabBarController? {
        findController(with: UITabBarController.self)
    }
    
    /// 根据类型查找控制器
    func findController<T: UIViewController>(with class: T.Type) -> T? {
        var responder = next
        while responder != nil {
            if responder!.isKind(of: `class`) {
                return responder as? T
            }
            responder = responder?.next
        }
        return nil
    }
    
    /// 设置新frame
    func setNewFrame(_ frame: CGRect) {
        if self.frame != frame {
            self.frame = frame
        }
    }
}

// MARK: - 动画
extension UIView {
    /// 抖动方向枚举
    enum ShakeDirection: Int {
        /// 水平抖动
        case horizontal
        /// 垂直抖动
        case vertical
    }
    
    /// 抖动
    /// - Parameters:
    ///   - direction: 抖动方向（默认是水平方向）
    ///   - times: 抖动次数（默认5次）
    ///   - interval: 每次抖动时间（默认0.1秒）
    ///   - delta: 抖动偏移量（默认2）
    ///   - completion: 抖动动画结束后的回调
    func shake(direction: UIView.ShakeDirection = .horizontal,
               times: Int = 5,
               interval: TimeInterval = 0.1,
               delta: CGFloat = 2,
               completion: (() -> Void)? = nil) {
        UIView.animate(withDuration: interval, animations: {
            switch direction {
            case .horizontal:
                self.layer.setAffineTransform(CGAffineTransform(translationX: delta, y: 0))
            case .vertical:
                self.layer.setAffineTransform(CGAffineTransform(translationX: 0, y: delta))
            }
        }) { _ in
            if times == 0 {
                UIView.animate(withDuration: interval, animations: {
                    self.layer.setAffineTransform(.identity)
                }, completion: { _ in
                    completion?()
                })
            } else {
                self.shake(direction: direction, times: times - 1, interval: interval, delta: delta * -1, completion: completion)
            }
        }
    }
}

// MARK: - 圆角
extension UIView {
    
    /// 添加圆角
    /// - Parameters:
    ///   - radius: 圆角半径
    ///   - width: 边框宽
    ///   - color: 边框颜色
    func addRoundedCorners(radius cornerRadius: CGFloat, width borderWidth: CGFloat = 0, color borderColor: UIColor = .clear) {
        layer.cornerRadius = cornerRadius
        layer.borderWidth = borderWidth
        layer.borderColor = borderColor.cgColor
        layer.masksToBounds = true
    }
    
    func addRoundedCorners(corner: UIRectCorner, cornerRadius: CGFloat) {
        addRoundedCorners(corner: corner, cornerRadius: cornerRadius, frame: bounds)
    }
    
    func addRoundedCorners(corner: UIRectCorner, cornerRadius: CGFloat, frame: CGRect) {
        let bezierPath = UIBezierPath(roundedRect: frame, byRoundingCorners: corner, cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
        let shapeLayer = CAShapeLayer()
        shapeLayer.frame = frame
        shapeLayer.path = bezierPath.cgPath
        layer.mask = shapeLayer
    }
}

// MARK: -
public extension Spadger where Base: UIView {
    /// 添加点击事件
    /// - Parameters:
    ///   - target: 监听对象
    ///   - selector: 方法
    func addTapGesture(_ target : Any ,_ selector : Selector) {
        let tap = UITapGestureRecognizer(target: target, action: selector)
        // 轻点次数
        tap.numberOfTapsRequired = 1
        // 手指个数
        tap.numberOfTouchesRequired = 1
        base.isUserInteractionEnabled = true
        base.addGestureRecognizer(tap)
    }
    
    
    /// 添加长按手势
    /// - Parameters:
    ///   - target: 监听对象
    ///   - selector: 方法
    func addLongGesture(_ target : Any ,_ selector : Selector, minimumPressDuration: TimeInterval = 0, allowableMovement: CGFloat = 50) {
        let long = UILongPressGestureRecognizer(target: target, action: selector)
        long.minimumPressDuration = 1.0 // 设置最小长按时间为1秒
        long.allowableMovement = 50 // 设置在触发长按前允许的最大移动距离为50点
        base.isUserInteractionEnabled = true
        base.addGestureRecognizer(long)
    }
    
    
}

extension UIView {
    /// 按照view大小截图
    var snapshot: UIImage? {
        UIGraphicsBeginImageContextWithOptions(bounds.size, true, UIScreen.main.scale)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}

// MARK: - UIView 有关 Frame 的扩展
public extension Spadger where Base: UIView {
    
    var x: CGFloat {
        get { base.frame.origin.x }
        set {
            var r = base.frame
            r.origin.x = newValue
            base.frame = r
        }
    }
    
    var maxX: CGFloat {
        get { base.frame.maxX }
        set {
            var r = base.frame
            r.origin.x = newValue - r.size.width
            base.frame = r
        }
    }
    
    var y: CGFloat {
        get { base.frame.origin.y }
        set {
            var r = base.frame
            r.origin.y = newValue
            base.frame = r
        }
    }
    
    var maxY: CGFloat {
        get { base.frame.maxY }
        set {
            var r = base.frame
            r.origin.y = newValue - base.frame.size.height
            base.frame = r
        }
    }
    
    var width: CGFloat {
        get { base.frame.width }
        set {
            var r = base.frame
            r.size.width = newValue
            base.frame = r
        }
    }
    
    var height: CGFloat {
        get { base.frame.height }
        set {
            var r = base.frame
            r.size.height = newValue
            base.frame = r
        }
    }
    
    var size: CGSize {
        get { base.frame.size }
        set {
            var r = base.frame
            r.size = newValue
            base.frame = r
        }
    }
    
    /// 视图的X中间位置
    var centerX: CGFloat {
        get { base.center.x }
        set {
            var center: CGPoint = base.center
            center.x = newValue
            base.center = center
        }
    }
    
    /// 视图Y的中间位置
    var centerY: CGFloat {
        get { base.center.y }
        set {
            var center: CGPoint = base.center
            center.y = newValue
            base.center = center
        }
    }
    
    /// 视图的中间位置
    var center: CGPoint {
        get { base.center }
        set {
            var center: CGPoint = base.center
            center = newValue
            base.center = center
        }
    }
}
